package com.manage.web.config.moreData;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 多数据源配置
 * @author duaiyu
 * @version V1.0
 * @date 2022/5/28
 * 来源：自研
 */
@Configuration
@MapperScan(
        /** 这里mapper有多个的时候，用第二种写法，只有一个时候用第一种
         *  本处的第二个包，是单独处理主数据库时候的mapper存放地址，
         *  操作多数据源的时候，存放到对应的两个地方
         */
        // basePackages = "com.manage.mapper.primary",
        basePackages = {"com.manage.mapper.primary", "com.manage.mapper.single"},
        sqlSessionFactoryRef = "sqlSessionFactoryPrimary",
        sqlSessionTemplateRef = "sqlSessionTemplatePrimary")
public class PrimaryConfig {
    private DataSource primaryDataSource;

    public PrimaryConfig(@Qualifier("primaryDataSource") DataSource primaryDataSource){
        this.primaryDataSource = primaryDataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryPrimary() throws  Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(primaryDataSource);
        //没有这行代码，会报错Invalid bound statement (not found)，多个xml包时候，用第二个
//        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
//                "classpath*:mapper/moreDataPrimary/*.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(
                "classpath*:mapper/*/*.xml"));
        return bean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplatePrimary() throws Exception{
        return new SqlSessionTemplate(sqlSessionFactoryPrimary());
    }
}
